<!DOCTYPE html>
<html>
<head>
    <title>工作计划</title>
    <meta name="keywords" content="keyword1,keyword2,keyword3">
    <meta name="description" content="this is my page">
    <meta name="content-type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="/static/plugin/layui/css/layui.css" media="all" />
    <link rel="stylesheet" href="/static/css/public.css" media="all" />
    <script type="text/javascript" src="/static/plugin/jquery/jquery-3.3.1.js"></script>
    <script type="text/javascript" src="/static/plugin/layui/layui.js"></script>
    <script type="text/javascript" src="/static/js/base.js"></script>
    <style type="text/css">
        .xing
        {
            color: red;
            float: left;
            display: block;
            width: 0.1%;
            margin-top:-25px;
            margin-left: 83%;
            font-size: 24px;
        }
    </style>
</head>
<script type="text/javascript"></script>
<body  class="layui-anim">
<div class="x-nav">
	    <span class="layui-breadcrumb">
	        <a href="">首页</a>
	        <a>
	            <cite>工作计划</cite>
	        </a>
	    </span>
</div>
<div class="x-body">
    <!--头部检索功能-->
    <div class="layui-row" style="margin-bottom: 18px">
        <form class="layui-form">
            <div class="layui-inline">
                <div class="layui-input-inline" style="float: left">
                    <select class="layui-input" name="keyword1" id="keyword1">
                        <option value="">请选择用户</option>
                    </select>
                </div>
                <button type="button" class="layui-btn layui-btn-normal" data-type="reload"><i class="layui-icon layui-icon-search"></i>检索</button>
            </div>
        </form>
    </div>

    <!--顶部功能-->
    <xblock>
        <button class="layui-btn layui-btn-warm" id="add"><i class="layui-icon layui-icon-add-circle-fine"></i>新增计划</button>
        <button class="layui-btn layui-btn-danger" id="del"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
        <!--<button class="layui-btn layui-btn-blue" id="approvel"><i class="layui-icon layui-icon-share"></i>提交审批</button>-->
        <button class="layui-btn layui-btn-danger" id="downLoad"><i class="layui-icon layui-icon-delete"></i>附件下载</button>
    </xblock>

    <!--数据列表-->
    <table class="layui-hide" id="tableList" lay-filter="tableList"></table>

    <!--行按钮-->
    <script type="text/html" id="rowToolbar">
        <a class="layui-btn layui-btn-xs" lay-event="update"><i class="layui-icon layui-icon-edit"></i>编辑</a>
    </script>

</div>
<!-- 添加/编辑框 -->
<div id="addDivID" style="display:none">
    <form class="layui-form" id="addFormID" style="margin-top:20px">
        <!--计划ID，编辑时用到，隐藏不显示-->
        <input type="hidden" id="planId" name="planId">
        <div class="layui-form-item">
            <div>
                <label class="layui-form-label">计划类型</label>
                <div class="layui-input-inline" style="width: 230px">
                    <select class="layui-input" name="planType" id="planType" lay-filter="planType" lay-verify="request" >
                        <option value="0">日计划</option>
                        <option value="1">周计划</option>
                        <option value="2">月计划</option>
                    </select>
                    <span class="xing" style="margin-left: 105%;">*</span>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">时间</label>
                <input class="layui-input" id="planTime" name="planTime" style="width: 230px">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">计划内容</label>
            <div class="layui-inline">
                <textarea id="planContent" name="planContent" rows="8" cols="20" wrap="hard" lay-verify="request" style="width: 230px"></textarea>
                <span class="xing" style="margin-left: 105%;">*</span>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">图片</label>
                <input class="layui-input" type="hidden" id="photoName" name="photoName" style="width: 230px">
                <div class="layui-upload layui-inline">
                    <button type="button" class="layui-btn" id="test1">上传图片</button>
                    <div class="layui-upload-list">
                        <img class="layui-upload-img" width="230px" height="200px" id="demo1">
                        <p id="demoText"></p>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">附件</label>
                <input class="layui-input" type="hidden" id="attachmentName" name="attachmentName" style="width: 230px">
                <div class="layui-upload layui-inline">
                    <button type="button" class="layui-btn" id="test3">上传附件</button>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">审批人</label>
            <div class="layui-inline" style="width: 230px">
                <select class="layui-input" name="approvalId" id="approvalId" lay-verify="request">
                    <option value="">请选择审批人</option>
                </select>
                <span class="xing" style="margin-left: 105%;">*</span>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">备注</label>
                <input class="layui-input" id="remark1" name="remark1" style="width: 230px">
            </div>
        </div>
        <div class="layui-form-item" align="center">
            <div>
                <button class="layui-btn" id="subBtn" lay-submit lay-filter="addForm">立即提交</button>
                <button  class="layui-btn layui-btn-primary">取消</button>
            </div>
        </div>
    </form>
</div>
<script type="text/javascript">
    layui.use(['table','layer','upload','form','laydate'], function(){
        var table = layui.table;
        var layer = layui.layer;
        var form = layui.form;
        var upload = layui.upload;

        /*检索按钮调用的方法*/
        var $ = layui.jquery, active = {
            reload:function () {
                var keyword01 = $("#keyword1").val();
                table.reload('contentTable',{
                    method:'get',
                    where:{"userId":keyword01}
                    ,page: {
                        curr: 1//重新从第 1 页开始
                    }
                });
            }
        }

        //普通图片上传
        var uploadInst = upload.render({
            elem: '#test1'
            ,url: '/work/upload'
            ,accept:'images'
            ,size:50000
            ,before: function(obj){
                obj.preview(function(index, file, result){
                    $('#demo1').attr('src', result);
                });
            }
            ,done: function(res){
                //如果上传失败
                if(res.code > 0){
                    return layer.msg('上传失败');
                }
                //上传成功
                var demoText = $('#demoText');
                demoText.html('<span style="color: #4cae4c;">上传成功</span>');
                //把路径存入表中
                $('#photoName').val(res.data);

                var fileupload = $(".image");
                fileupload.attr("value",res.data.src);
                console.log(fileupload.attr("value"));
            }
            ,error: function(){
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function(){
                    uploadInst.upload();
                });
            }
        });

        //指定允许上传的文件类型
        upload.render({
            elem: '#test3'
            ,url: '/work/uploadFile' //改成您自己的上传接口
            ,accept: 'file' //普通文件
            ,done: function(res){
                console.log(res);
                if(res.code > 0){
                    layer.msg('上传失败');
                }else{
                    layer.msg('上传成功');
                    //把路径存入表中
                    $('#attachmentName').val(res.data);
                }
            }
        });

        //点击行checkbox选中
        $(document).on("click",".layui-table-body table.layui-table tbody tr", function () {
            var index = $(this).attr('data-index');
            var tableBox = $(this).parents('.layui-table-box');
            //存在固定列
            if (tableBox.find(".layui-table-fixed.layui-table-fixed-l").length>0) {
                tableDiv = tableBox.find(".layui-table-fixed.layui-table-fixed-l");
            } else {
                tableDiv = tableBox.find(".layui-table-body.layui-table-main");
            }
            var checkCell = tableDiv.find("tr[data-index=" + index + "]").find("td div.laytable-cell-checkbox div.layui-form-checkbox I");
            if (checkCell.length>0) {
                checkCell.click();
            }
        });

        $(document).on("click", "td div.laytable-cell-checkbox div.layui-form-checkbox", function (e) {
            e.stopPropagation();
        });

        $('.layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        /*班组类型数据列表*/
        table.render({
            elem: '#tableList'
            ,url:'/work/queryWorkPlan'
            ,title: '工作计划'
            ,id :'contentTable'
            ,limits:[10,20,30]
            ,toolbar: '#toolbar'
            ,cols: [
                [
                    {type: 'checkbox', fixed: 'left'}
                    ,{field:'planId', title:'序号', sort: true, type:'numbers', width: 60}
                    ,{field:'createName', title:'姓名'}
                    ,{field:'planType', title:'计划类型', templet: function (row){
                        if(row.planType == 0){
                            return "日计划";
                        } else if(row.planType == 1){
                            return "周计划";
                        }else{
                            return "月计划";
                        }
                    }}
                    ,{field:'planTime', title:'计划时间', width: 200}
                    ,{field:'planContent', title:'计划内容'}
                    ,{field:'photoName', title:'图片', templet: function(d) {
                        var url = d.photoName == undefined ? "" : d.photoName;
                        return '<a href="' + url + '" target="_blank " title="点击查看">' +
                            '<img src="' + url + '" style="height:20px;" />' +
                            '</a>';
                    }}
                    ,{field:'attachmentName', title:'附件', templet: function(d) {
                        return d.attachmentName == undefined ? false : true;
                    }}
                    ,{field:'remark', title:'备注'}
                    ,{field:'planStatus', title:'计划状态', templet: function (row){
                        if(row.planStatus == 0){
                            return "未审阅";
                        } else if(row.planStatus == 1){
                            return "通过";
                        }else{
                            return "驳回";
                        }
                    }}
                    ,{field:'approvalOpinion', title:'审阅意见'}
                    ,{field:'approvalTime', title:'审阅时间'}
                    ,{fixed:'right',unresize: true, title:'操作', toolbar: '#rowToolbar',width:100, align: 'center'}
                ]
            ]
            ,page: true
            ,done : function(){
                $('th').css({
                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                })
            }
        });

        //监听复选框事件
        table.on('checkbox(tableList)',function(obj){
            if(obj.checked == true && obj.type == 'all'){
                //点击全选
                $('.layui-table-body table.layui-table tbody tr').addClass('layui-table-click');
            }else if(obj.checked == false && obj.type == 'all'){
                //点击全不选
                $('.layui-table-body table.layui-table tbody tr').removeClass('layui-table-click');
            }else if(obj.checked == true && obj.type == 'one'){
                //点击单行
                if(obj.checked == true){
                    obj.tr.addClass('layui-table-click');
                }else{
                    obj.tr.removeClass('layui-table-click');
                }
            }else if(obj.checked == false && obj.type == 'one'){
                //点击全选之后点击单行
                if(obj.tr.hasClass('layui-table-click')){
                    obj.tr.removeClass('layui-table-click');
                }
            }
        })


        /**
         * 表单校验
         */
        form.verify({
            //value：表单的值、item：表单的DOM对象
            request: function(value, item){
                if(value == ''){
                    return '不能为空';
                }
            }
        });

        //新增
        $("#add").click(function(){
            layer.open({
                type: 1 					//Page层类型
                ,area: ['500px', '700px'] 	//宽  高
                ,title: '新增'
                ,shade: 0.6 				//遮罩透明度
                ,maxmin: true 				//允许全屏最小化
                ,anim: 1 					//0-6的动画形式，-1不开启
                ,content:$('#addDivID')
                ,success: function(){
                    $("#planId").val("");
                    //初始化数据
                    $("#addFormID").find('input[class=layui-input],select').each(function() {
                        $(this).val('');
                    });
                    form.render();
                }
            });
        });

        //行按钮(编辑)
        table.on('tool(tableList)', function(obj){
            var data = obj.data;
            /*编辑*/
            if (obj.event === 'update') {
                if(data.planStatus > 0){
                    layer.msg("已审阅，不能修改！",{icon:6});
                    return false
                }
                layer.open({
                    type: 1 					//Page层类型
                    ,area: ['500px', '600px'] 	//宽  高
                    ,title: '编辑'
                    ,shade: 0.6 				//遮罩透明度
                    ,maxmin: true 				//允许全屏最小化
                    ,anim: 1 					//0-6的动画形式，-1不开启
                    ,content:$('#addDivID')
                    ,success: function(){
                        //数据回显
                        for(var i=0;i<Object.entries(data).length;i++) {
                            var id = '#' + Object.entries(data)[i][0];
                            var text = Object.entries(data)[i][1];
                            $(id).val(text);
                        }
                        form.render();
                    }
                });
            }
        });

        //批量删除
        $("#del").click(function(){
            var rowData = table.checkStatus('contentTable');
            var data = rowData.data;
            var idArr = new Array();
            if(data.length == 0){
                layer.alert("请至少选择一条记录！",{icon :5});
            } else {
                var ids="";
                for(var i=0;i<data.length;i++){
                    if(ids == ""){
                        ids += data[i].planId;
                    }else{
                        ids += "," + data[i].planId;
                    }
                    if(data[i].planStatus > 0){
                        layer.msg("已审阅，不能删除！",{icon:6});
                        return false
                    }
                }
                layer.confirm('确定删除吗？', function(){
                    $.ajax({
                        type:'post',
                        url:'/work/deleteWorkPlan',
                        data:{"ids" : ids},
                        dataType:"json",
                        success:function(data){
                            if(data > 0){
                                layer.msg("删除成功！",{icon:6});
                                layer.closeAll();
                                table.reload('contentTable',{
                                    method:'get',
                                    page: {
                                        curr: 1//重新从第 1 页开始
                                    }
                                });
                            }else{
                                layer.msg("删除失败！",{icon:5});
                                layer.closeAll();
                                table.reload('contentTable',{
                                    method:'get',
                                    page: {
                                        curr: 1//重新从第 1 页开始
                                    }
                                });
                            }
                        }
                    });
                });
            }
        });

        /**
         * 下载附件
         */
        $("#downLoad").click(function(){
            var rowData = table.checkStatus('contentTable');
            var data = rowData.data;
            var url = data[0].attachmentName;
            if(data.length == 1){
                if(url == undefined){
                    layer.alert("没有上传附件，无法下载！",{icon :5});
                }else{
                    var href = "/work/downLoad?path=" + url;
                    window.location.href = href;
                }
            } else {
                layer.alert("请选择一条记录！",{icon :5});
            }
        });

        /**
         * 表单提交(新增、编辑)
         */
        form.on('submit(addForm)', function () {
           // var index = layer.msg('提交中，请稍候',{icon: 16,time:false,shade:0.8});
            var title = "新增";
            var url = '/work/insertWorkPlan';
            var id = $.trim($("#planId").val());
            if(id != "" && id != null && id != 'undefined'){
                title = "编辑";
                url = '/work/updateWorkPlan';
            }
            $.ajax({
                type:'post',
                url:url,
                data:$("#addFormID").serialize(),
                cache:false,
                dataType: 'JSON',
                success:function(data){
                    if (data > 0) {
                        layer.closeAll();
                        setTimeout(function(){
                            layer.msg(title+'成功！',{icon:6});
                        },1000);
                        table.reload('contentTable',{
                            method:'get',
                            page: {
                                curr: 1//重新从第 1 页开始
                            }
                        });
                    } else {
                        layer.msg(title+'失败！',{icon:5});
                        layer.close(index);
                    }
                }
            });
            return false;
        })

        /**
         * 下拉框监听事件，根据计划类型，自动生成计划日期
         */
        form.on('select(planType)', function(param){
            var value = "";
            if(param.value == 0){
                value = getDateStr3(new Date());
            }else if(param.value == 1){
                value = getWeekStartAndEnd(0);
            }else{
                value = getMonthStartAndEnd(0);
            }
            $('#planTime').val(value);
        })

    });

    /*下拉框查找所有用户*/
    function addSelectUser() {
        $('#principalId').empty();
        $.ajax({
            type: 'POST',
            url: '/work/getAllUser',
            dataType: 'json',
            async: false,
            success: function (datas){
                for (var i = 0; i < datas.length; i++) {
                    $("#keyword1").append("<option value='"+ datas[i].userId +"'>"+ datas[i].realName +"</option>");
                    $("#approvalId").append("<option value='"+ datas[i].userId +"'>"+ datas[i].realName +"</option>");
                }
            }
        });
    }

    /**
     * 获取当前日期yy-mm-dd
     * **/
    function getDateStr3(data) {
        var year = "";
        var month = "";
        var day = "";
        var now = data;
        year = ""+now.getFullYear();
        if((now.getMonth()+1)<10){
            month = "0"+(now.getMonth()+1);
        }else{
            month = ""+(now.getMonth()+1);
        }
        if((now.getDate())<10){
            day = "0"+(now.getDate());
        }else{
            day = ""+(now.getDate());
        }
        return year+"-"+month+"-"+day;
    }
    /**
     * 获得相对当前周AddWeekCount个周的起止日期
     * AddWeekCount为0代表当前周  为-1代表上一个周  为1代表下一个周以此类推
     * **/
    function getWeekStartAndEnd(AddWeekCount) {
        //一天的毫秒数
        var millisecond = 1000 * 60 * 60 * 24;
        //获取当前时间
        var currentDate = new Date();
        //相对于当前日期AddWeekCount个周的日期
        currentDate = new Date(currentDate.getTime() + (millisecond * 7*AddWeekCount));
        //返回date是一周中的某一天
        var week = currentDate.getDay();
        //返回date是一个月中的某一天
        var month = currentDate.getDate();
        //减去的天数
        var minusDay = week != 0 ? week - 1 : 6;
        //获得当前周的第一天
        var currentWeekFirstDay = new Date(currentDate.getTime() - (millisecond * minusDay));
        //获得当前周的最后一天
        var currentWeekLastDay = new Date(currentWeekFirstDay.getTime() + (millisecond * 6));
        //添加至数组
        var re = getDateStr3(currentWeekFirstDay) + "~" + getDateStr3(currentWeekLastDay);
        return re;
    }
    /**
     * 获得相对当月AddMonthCount个月的起止日期
     * AddMonthCount为0 代表当月 为-1代表上一个月 为1代表下一个月 以此类推
     * ***/
    function getMonthStartAndEnd(AddMonthCount) {
        //获取当前时间
        var currentDate = new Date();
        var month=currentDate.getMonth()+AddMonthCount;
        if(month<0){
            var n = parseInt((-month)/12);
            month += n*12;
            currentDate.setFullYear(currentDate.getFullYear()-n);
        }
        currentDate = new Date(currentDate.setMonth(month));
        //获得当前月份0-11
        var currentMonth = currentDate.getMonth();
        //获得当前年份4位年
        var currentYear = currentDate.getFullYear();
        //获得上一个月的第一天
        var currentMonthFirstDay = new Date(currentYear, currentMonth,1);
        //获得上一月的最后一天
        var currentMonthLastDay = new Date(currentYear, currentMonth+1, 0);
        var re = getDateStr3(currentMonthFirstDay) + "~" + getDateStr3(currentMonthLastDay);
        //返回
        return re;
    }

    window.onload = addSelectUser();
</script>
</body>
</html>
